package com.ts.animal.service.impl;

import com.ts.animal.constant.AnimalConstant;
import com.ts.animal.service.BaseStationService;
import com.ts.common.redis.RedisUtil;
import com.ts.system.base.BaseInterface;
import com.ts.system.domain.SystemParamsDO;
import com.ts.system.util.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ResolveBaseStationDataService implements BaseInterface {

    private static Logger log = LoggerFactory.getLogger(ResolveBaseStationDataService.class);
    static ResolveBaseStationDataService resolveBaseStationDataService;
    @Autowired
    private BaseStationService baseStationService;

    public static void main(String[] args) {
        resolveBaseStationDataService = new ResolveBaseStationDataService();
        resolveBaseStationDataService.init();
    }

    @Override
    public void init() {
        //接收基站数据线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        SystemParamsDO paramsDO = SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_resolve_switch);
                        if (paramsDO != null && paramsDO.getParamValue().equalsIgnoreCase(AnimalConstant.open)) {
                            long size = RedisUtil.listSize(AnimalConstant.REDIS_BASE_STATION_DATA_KEY);
                            //从redis中拿到基站发出的数据
                            String dataString = RedisUtil.rpop(AnimalConstant.REDIS_BASE_STATION_DATA_KEY, String.class);
                            log.info("当前从Redis中取基站同步的数据，Redis中数据长度为{},当前取的数据是：{}", size, dataString);
                            baseStationService.resolveData(dataString);

                            if (RedisUtil.listSize(AnimalConstant.REDIS_BASE_STATION_DATA_KEY) == 0) {
                                log.info("Redis没有数据，休眠20秒钟");
                                Thread.sleep(20000l);
                            }
                        } else {
                            log.info("解析服务暂停，休眠30秒钟");
                            Thread.sleep(30000l);
                        }

                    } catch (Exception e) {
                        log.info("取数据异常，休眠30秒钟");
                        try {
                            Thread.sleep(30000l);
                        } catch (Exception ex) {
                        }
                        log.error("取数据异常:{}", e.getMessage());
                    }
                }
            }
        }).start();
    }

    public static ResolveBaseStationDataService getResolveBaseStationDataService() {
        return resolveBaseStationDataService;
    }

}
